package org.rxc.gift.service.impl;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import io.seata.spring.annotation.GlobalTransactional;
import org.rxc.gift.clients.AuthClient;
import org.rxc.gift.domain.Employee;
import org.rxc.gift.domain.LoginUser;
import org.rxc.gift.domain.Tenant;
import org.rxc.gift.domain.TenantMeal;
import org.rxc.gift.dto.TenantAdminDTO;
import org.rxc.gift.dto.TenantRegisterDTO;
import org.rxc.gift.exception.BusinessException;
import org.rxc.gift.exception.ResponseCode;
import org.rxc.gift.exception.RonghuaAssert;
import org.rxc.gift.mapper.EmployeeMapper;
import org.rxc.gift.mapper.TenantMapper;
import org.rxc.gift.mapper.TenantMealMapper;
import org.rxc.gift.service.ITenantService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.rxc.gift.util.AjaxResult;
import org.rxc.gift.util.BaiduAuditUtils;
import org.rxc.gift.util.EmailUtil;
import org.rxc.gift.util.encrypt.MD5;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author rxc
 * @since 2024-05-29
 */
@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements ITenantService {


    @Autowired
    private TenantMapper tenantMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private TenantMealMapper tenantMealMapper;


    @Autowired
    private AuthClient authClient;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private EmailUtil emailUtil;

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public void settlement(TenantRegisterDTO dto) {
        //1.数据校验
        TenantAdminDTO admin = dto.getAdmin();
        //非空校验
        //校验手机号是否已存在
        Wrapper<Employee> wrapper = new EntityWrapper<Employee>().eq("phone", admin.getPhone()).or().eq("username",admin.getUsername());
        List<Employee> employees = employeeMapper.selectList(wrapper);
        RonghuaAssert.isNull(employees,ResponseCode.RESPONSE_CODE_115);
        //两次密码比对
        RonghuaAssert.isEq(admin.getPassword(), admin.getConfirmPassword(), ResponseCode.RESPONSE_CODE_100);
        //检验租户名称是否重复
        //查询租户信息
        Tenant tenants =  tenantMapper.loadByName(dto.getCompanyName());
        //查询到租户信息,表示租户名称已存在，返回错误信息
        RonghuaAssert.isNull(tenants,ResponseCode.RESPONSE_CODE_101);
       //文本,图片审核
        List<String> texts = Arrays.asList(dto.getAddress(),dto.getCompanyName());
        List<String> images = Arrays.asList(dto.getLogo());
        Map<String,Object> resultMap= BaiduAuditUtils.censor(texts,images);
        Boolean flag = (Boolean) resultMap.get("success");

       //2.保存租户信息到数据库
        Tenant tenant = new Tenant();
        //将dto获取数据校验的店铺入驻信息复制给tenant
        BeanUtils.copyProperties(dto,tenant);
        //入驻的时间
        tenant.setRegisterTime(new Date());
        //审核状态
        tenant.setState(0);
        tenantMapper.insert(tenant);

        //保存租户套餐
        TenantMeal tenantMeal = new TenantMeal();
        tenantMeal.setTenantId(tenant.getId());
        tenantMeal.setMealId(dto.getMealId());
        tenantMealMapper.insert(tenantMeal);


        //3.保存管理员信息到数据库
        //保存管理员信息到登录信息表
        //MD5对盐值和密码加密
        String salt = UUID.randomUUID().toString().replaceAll("-","");
        String password = MD5.getMD5("ronghua"+salt+admin.getPassword()+"okok");
        LoginUser loginUser = new LoginUser();
        loginUser.setUsername("rh_"+UUID.randomUUID().toString().replaceAll("-",""));
        loginUser.setSalt(salt);
        loginUser.setPassword(password);
        loginUser.setPhone(dto.getCompanyNum());
        loginUser.setEmail(admin.getEmail());
        loginUser.setType(0);
        AjaxResult ajaxResult = authClient.addOrUpdate(loginUser);
        //判断
        if (!ajaxResult.isSuccess()){
            throw new BusinessException(ajaxResult.getMessage());
        }
        Long loginId = Long.parseLong(ajaxResult.getResultObj().toString());
        //保存管理员信息
        Employee employee = new Employee();
        BeanUtils.copyProperties(admin,employee);
        employee.setTenantId(tenant.getId());
        employee.setType(3);
        employee.setSalt(salt);
        employee.setPassword(password);
        employee.setLoginId(loginId);
        employeeMapper.insert(employee);

        //5.自动审核店铺入驻信息
        if(flag){
            //审核通过
            //发送一封激活邮件
            // 激活邮件
            String text = "<a href='http://localhost:20030/tenant/active/" + tenant.getId() + "/" + employee.getId() + "'>审核已通过,点击激活</a>";
            String uuid = UUID.randomUUID() + "-" + tenant.getId();
            redisTemplate.opsForValue().set(tenant.getId().toString(),uuid,30, TimeUnit.MINUTES);
            try {
                emailUtil.send("审核通过",text,employee.getEmail());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else {
            //审核不通过
            //发送一封入驻失败的邮件，并告知审核不通过的原因
            // 失败邮件
            try {
                emailUtil.send("审核未通过","很抱歉，您的店铺审核资料未通过",employee.getEmail());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void active(Long id, Long employeeId) {
        Object o = redisTemplate.opsForValue().get(id.toString());
        RonghuaAssert.isNotNull(o, ResponseCode.RESPONSE_CODE_116);
        Tenant tenant = tenantMapper.getById(id);
        tenant.setState(1);
        Employee employee = employeeMapper.getById(employeeId);
        employee.setState(0);
        employeeMapper.updateById(employee);
        tenantMapper.updateById(tenant);

    }

}
